<?php
class ImportdataAction extends CommonAction {
    function _filter(&$map){
        $map['userid'] = array('eq',session("userid"));
        //$map['wymc'] = array('like',"%".$_POST['wymc']."%");
    }
    public function index() {
        //列表过滤器，生成查询Map对象
        $map = $this->_search();
        if (method_exists($this, '_filter')) {
            $this->_filter($map);
        }
        //$name = $this->getActionName();
        $model = D('Upexcel');
        if (!empty($model)) {
            $this->_list($model, $map);
        }

        //读取试卷信息列表
        $exinfo     = D('ExaminfoView');
        $list_ex    = $exinfo->field('id,exName,exCount,createtime,subjectName')->order('id desc')->select();
        //dump($exinfo);
        if(!empty($exinfo)){
            $this->assign('exinfo',$list_ex);
        }
        //echo $exinfo->getLastsql();
        $this->display();
        return;
    }
    
    public function upExcel(){
    	import('ORG.Net.UploadFile');
		$upload 			= new UploadFile();// 实例化上传类
		$upload->maxSize  	= C('upMaxSize') ;// 设置附件上传大小
		$upload->allowExts  = array('xls', 'xlsx');// 设置附件上传类型
		$upload->savePath 	=  C('upPath').'excel/';// 设置附件上传目录
		if(!$upload->upload()) {// 上传错误提示错误信息
			$this->error($upload->getErrorMsg());
		}else{// 上传成功 获取上传文件信息
			$info =  $upload->getUploadFileInfo();
			//print_r($info);
			$upexcel 	= D('Upexcel');
			$data["filename"]	= $info[0]["savename"];
			$data["fileext"]	= $info[0]["extension"];
			$data["hash"]		= $info[0]["hash"];
			$data["filesize"]	= $info[0]["size"];
			$data["filepath"]	= $info[0]["savepath"];
            $data["showname"]   = $_REQUEST['showname'];
			$data['createtime'] = NOW_TIME;
			$data['userid']		= session('userid');
			$data['username']	= session('username');
			$upexcel->add($data);
			if(false!==$upexcel){
				$this->success('上传成功!',"__URL__");
			}else{
				$this->error('上传失败！',"__URL__");
			}
		}
    }
     public function foreverdelete() {
        //删除指定记录
        $model = D("Upexcel");
        if (!empty($model)) {
            $pk = $model->getPk();
            $id = $_REQUEST [$pk];
            if (isset($id)) {
                $condition = array($pk => array('in', explode(',', $id)));
                if (false !== $model->where($condition)->delete()) {
                	
                    $this->success('删除成功！',true);
                } else {
                    $this->error('删除失败！',false);
                }
            } else {
                $this->error('非法操作',false);
            }
        }
        $this->forward();
    }

    public function forbid() {
        //$name = $this->getActionName();
        $model = D('Upexcel');
        $pk = $model->getPk();
        $id = $_REQUEST [$pk];
        $condition = array($pk => array('in', $id));
        $list = $model->forbid($condition);
        if ($list !== false) {
            $this->assign("jumpUrl", $this->getReturnUrl());
            $this->success('状态禁用成功');
        } else {
            $this->error('状态禁用失败！');
        }
    }
    function resume() {
        //恢复指定记录
        //$name = $this->getActionName();
        $model  = D('Upexcel');
        $pk     = $model->getPk();
        $id     = $_GET [$pk];
        $condition = array($pk => array('in', $id));
        if (false !== $model->resume($condition)) {
            $this->assign("jumpUrl", $this->getReturnUrl());
            $this->success('状态恢复成功！');
        } else {
            $this->error('状态恢复失败！');
        }
    }

    function importexcel(){
        $filename   = I('filename');//电子表格文件名
        $id         = I('id');//试卷ID
        $fieldList  = 'id,stuid,schoolid,stuno;';
        $knl1 = array();
        $knl2 = array();
        $abl1 = array();
        $abl2 = array();
        $value1 = array();


        //读取试卷信息，根据试卷生成相应的表格，主要是显示有哪里知识点与能力点要生成单独的列
        //将各个学生的相应知识点或者能力点的值进行统计（加法求和）放入相应的列
        //是否还要保存原始的数据？暂时不，直接放excel里面保存，不放数据库。
        //还要加强：导入是累加还是重新建表？每次更新试卷信息后要重新建表???????????????????????????????????????????
        $Examinfo   = M("Examinfo");
        $Examinfo_vo = $Examinfo->select($id);
        $tableName  = 'score'.$id;
        $sql        = "CREATE TABLE if not exists `xspj_$tableName` (
                          `id` int(5) NOT NULL AUTO_INCREMENT,
                          `stuid` int(7) DEFAULT NULL,
                          `schoolid` int(3) DEFAULT NULL,
                          `school` varchar(20) DEFAULT NULL,
                          `stuname` varchar(10) DEFAULT NULL,
                          `stusex` varchar(1) DEFAULT NULL,
                          `stuno` varchar(15) DEFAULT NULL,";

        //取得所有的知识点名称，建立相应的列
        $knowledgeList = $Examinfo_vo[0]['knowledgeList'];
        $k1     = explode(';',$knowledgeList);
        foreach ($k1 as $k11) {
            $k111 = explode('#',$k11);
            if($k111[1]!=''){
                $sql .= "`". $k111[1] ."` tinyint(3) DEFAULT NULL,";
                $fieldList .= $k111[1].',';
                array_push($knl2,$k111[2]);
                array_push($knl1,$k111[1]);
            }
        }

        //在fieldList最后一个‘，‘去掉并加上';'
        $fieldList = substr($fieldList,0,strlen($fieldList)-1); 
        $fieldList .= ';';

        //取得所有的能力点名称，建立相应的列
        $abilityList = $Examinfo_vo[0]['abilityList'];
        $a1     = explode(';',$abilityList);
        foreach ($a1 as $a11) {
            $a111 = explode('#',$a11);
            if($a111[1]!=''){
                $sql .= "`". $a111[1] ."` tinyint(3) DEFAULT NULL,";
                $fieldList .= $a111[1].',';
                array_push($abl2,$a111[2]);
                array_push($abl1,$a111[1]);
            }
        }

        //在fieldList最后一个‘，‘去掉并加上';'
        $fieldList = substr($fieldList,0,strlen($fieldList)-1); 
        //$fieldList .= ';';

        $sql    .= "PRIMARY KEY (`id`)
                         ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";

        $model      = new Model();
        //$model->execute("DROP TABLE IF EXISTS xspj_$tableName");
        $model->execute($sql);

        //将fieldList数据存入表格
        $data['fieldList']=$fieldList;
        $Examinfo->data($data)->where('id='.$id)->save();

        //读取excel数据
        vendor('PHPExcel176.PHPExcel');
        $f      = C('upPath').'excel/'. $filename;
        $res    = $this->excelToArray1($f);

        //注意，这里还要加上一个判断试卷类型是否对的上的判断????????????????????????????????????????????!!!!!!!

        //每个学生的各知识点和值放到临时表的相应字段内
        //第一个for是行数，第二个for是列数,数据从第四行开始
        $hh = 4;
        $ll = 4;
        //测试这个学校的数据是否已经导入
        $score = M($tableName);
        if($score->where("school='".$res[$hh][1]."'")->find()){
            echo '该学校数据已经导入!<br>请勿重复导入!';
            //echo $score->getlastsql();
            return;
        };
        //生成socre表格内数据/////////////////////////////////////////
        //$tempschool用于去school查询学校id，为了不每一个相同的学校都去查一次，用一个临时字段，下一个相同时不查
        $tempschool     = $res[$hh][2];;
        //$tempschoolid   = '';
        for($i=$hh;$i<=sizeof($res);$i++){
            $value1['school']   = $res[$i][1];
            $value1['stuname']  = $res[$i][2];
            $value1['stusex']   = $res[$i][3];

            if($tempschoolid==''||$tempschool!=$value1['school']){
                $school     = M('School');
                $s_map['sName|showNames'] = array('like','%'.$value1['school'].'%');
                $re_school  = $school->where($s_map)->select();
                if($re_school){
                    $tempschoolid   = $re_school[0]['id'];
                    //echo $school->getLastsql();
                    //dump($re_school);
                    $tempschool     = $value1['school'];
                    
                }
            }
            $value1['schoolid']   = $tempschoolid;

            for($j=$ll;$j<sizeof($res[$i]);$j++){                
                foreach ($knl2 as $key => $val) {
                    if(strpos(('#,'.$val),','.($j-$ll+1).',')>0){
                        $value1[$knl1[$key]] += $res[$i][$j];
                    }
                }
                foreach ($abl2 as $key => $val) {
                    if(strpos(('#,'.$val),','.($j-$ll+1).',')>0){
                        $value1[$abl1[$key]] += $res[$i][$j];
                    }
                }
            }
            $score->data($value1)->add();
            unset($value1);
        }
        echo ($i-$hh)."条记录导入成功！";
    }

}

?>